import java.util.PriorityQueue;
import java.util.concurrent.Executors;

//interface Mytimertask extends Runnable {
//
//}

class MyTimertask implements Comparable<MyTimertask>{

    private Runnable runnable;
    private long time;

    public MyTimertask(Runnable r, long t) {
        this.runnable = r;
        this.time = t;
    }

    @Override
    public int compareTo(MyTimertask o) {
        return (int)(this.time - o.time);
    }

    public void getRunnable() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }
}

class MyTimer {

    PriorityQueue<MyTimertask> p = new PriorityQueue<>();

    Object locker = new Object();

    public void schedule(Runnable runnable, long t) {

        synchronized (locker) {
            MyTimertask m = new MyTimertask(runnable,t + System.currentTimeMillis());
            p.offer(m);
            locker.notify();
        }

    }

    public MyTimer() {
        Thread t = new Thread(() -> {


                    try {

                        while (true) {
                            synchronized (locker) {
                                while (p.isEmpty()) {
                                    locker.wait();
                                }
                                MyTimertask k = p.peek();
                                if (System.currentTimeMillis() < k.getTime()) {
                                    locker.wait(k.getTime() - System.currentTimeMillis());

                                } else {
                                    k.getRunnable();
                                    p.poll();
                                }
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }



        });
        t.start();
    }
}

public class Demo2 {

    public static void main(String[] args) {

        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);

        System.out.println("hello main");
        Executors.newFixedThreadPool(4);
    }
}
